import re
import requests
import json
from requests_toolbelt import MultipartEncoder
from frame_work.type_file import (
    SourceOrderWay,
    highQualitySource,
    EnterType
)
from frame_work.setting import *
from frame_work.logger import Logger
from frame_work.util import (
    change_user_account_status,
    get_binded_shop_list,
    bind_shop,
    get_seller_level,
    get_order_url,
    assert_result_dict
)
from frame_work.login import PcLogin
from frame_work import menu_list
from workspace.shikee.chuji.pay import PayQuantity
from workspace.shikee.high_quality_goods.release_high_quality_batch import Activity as batch_activity
from frame_work.yaml_file import YAML
from frame_work.release_util import high_quality_release

logger = Logger(__name__).get_logger()


class Activity(object):

    def __init__(self, uname):
        self.uname = uname
        self.session = self.get_session()
        self.yaml = YAML(os.path.join(base_Dir, 'data', 'data.yaml'))

    def get_session(self):
        """
        :return:返回登录session
        """
        login = PcLogin(self.uname)
        login.pc_login()
        return login.get_session()

    def get_html(self):
        """
        请求一个页面，在响应中获取比如：token，shopId等
        :return: html
        """
        url = self.yaml.get_data("token").get('url')
        html = self.session.get(url).text
        return html

    def get_token(self):
        """
        从html中通过正则表达式获取token
        :return:token
        """
        complex_value = 'name="token" value="(.*?)"'
        html = self.get_html()
        token = re.findall(complex_value, html)
        try:
            token = token[0]
            logger.debug('获取token值 => %s ...' % token)
        except (IndexError, KeyError) as e:
            logger.debug("获取token出错")
            return False
        else:
            return token

    @staticmethod
    def echo_task(source):
        """
        根据来源,输出增值任务数组类型
        :param source:
        :return:
        """
        if source in (1, 2):
            return [4, 8, 16, 32, 64, 128]
        elif source in (5, 12, 15):
            return [8, 16, 32, 64, 128]
        elif source == 13:
            return [8, 16, 64, 128]
        elif source == 8:
            return [8, 16, 32, 128]
        elif source == 14:
            return [8, 16, 32, 64]

    def get_pic(self, num):
        """
        发布活动中会含有上传图片的操作，此函数在作用post一张图片到图片服务器，获取tmp address类似：tmp/2019/08/20/08500820924072552490.jpg
        :param num:第几张图片
        :return:pic_addr
        """
        shikee_cookies = self.session.cookies.get(
            'shikee')  # 获取用户cookies中的shikee部分
        yaml_data = self.yaml.get_data("echo_tmp_pic_address")
        yaml_data.get('data').update({
            'id': 'WU_FILE_' + str(num),  # num:发布活动页面有多个上传图片地方,用于区别
            'Filedata': ('filename', open(os.path.join(image_Path, '精品试用活动.png'), 'rb'), 'image/png')
        })
        m = MultipartEncoder(
            fields=yaml_data.get('data')
        )
        r = requests.post(yaml_data.get('url') + '/1?swf_upload_cookie=' + shikee_cookies, data=m,
                          headers={'Content-Type': m.content_type})
        return r.text

    @staticmethod
    def echo_source():
        """
        列出活动来源,用户自己选择
        :return:source
        """
        for index, i in enumerate(highQualitySource.source.value, start=1):
            print(index, ''.join(list(i.keys())))
        try:
            choise_source = int(input("请选择活动来源选项:\t\n---->  "))
        except BaseException as e:
            logger.error('输入选项错误，请选择对应序号')
        else:
            if choise_source > len(highQualitySource.source.value):
                logger.error('超出选项范围')
                return False
            else:
                source = list(
                    highQualitySource.source.value[choise_source - 1].values())
                # [数组形式]
                return source[0]

    @staticmethod
    def echo_enter_type(source):
        """
        列出进店方式,用户自主选择
        :param source:活动来源
        :return:e_type
        """
        for index, enter_type in enumerate(
                SourceOrderWay[highQualitySource(source).name].value, start=1):
            print("%s : %s" % (index, enter_type))
        try:
            choise_source = int(
                input("请选择下单进店方式选项(可多选，直接输入对应序号(例如:123)):\t\n---->  "))
        except BaseException as e:
            logger.error('输入选项错误，请选择对应序号')
        else:
            # 最终确定以数组形式的进店方式，例如[1,2,16,32]
            e_type = [EnterType[SourceOrderWay[highQualitySource(source).name].value[int(
                i) - 1]].value for i in str(choise_source).strip()]
            return e_type

    def release_basic(self, *args, **kwargs):
        """
        发布封装
        :param args:
        :param kwargs:
        :return:
        """
        value = get_seller_level(self.uname)
        level = value[0].get("level")
        if level not in [4, 11, 12]:
            logger.info("非紫金/王者/星耀vip不能发布精品试用")
            return
        source = kwargs.get("source")
        source_cn = highQualitySource(source).name  # 枚举类通过value反向获取name
        source_cn = '淘特' if source_cn == '淘宝特价版' else source_cn
        value = get_binded_shop_list(self.uname, source_cn)
        if not value:
            bind_shop(source_cn, self.uname)
            value = get_binded_shop_list(self.uname, source_cn)
        # enter_type = kwargs.get("enter_type")
        title = source_cn + '_精品深度' + '_自选进店_刘'
        url, post_data, header = high_quality_release(
            enter_type=kwargs.get("enter_type"),
            qr_search_pic=json.loads(self.get_pic(2)).get('data'),
            qr_order_pic=json.loads(self.get_pic(3)).get('data'),
            # 'try_extend[added_task][]'=Activity.echo_task(source),  # 根据活动来源,来判断用什么增值方式
            source=source, token=self.get_token(),
            shopId=value[0].get("sid"),
            shop_name=value[0].get("name"),
            Title=title,
            url_order=kwargs.get("order_url"),
            title_pic=json.loads(self.get_pic(0)).get('data'),
            search_pic=json.loads(self.get_pic(1)).get('data')
            # GrantNum = sum([yaml_data.get("data").get("try_extend_enter[%s][total]" % t) for t in
            #                 enter_type])  # 根据每个进店方式的份数计算总份数，进店方式是根据用户自己选择的
        )
        logger.debug('开始发布' + source_cn + '_精品试用')
        response = self.session.post(url, data=post_data, headers=header).text
        status = assert_result_dict(
            response, "vip商家" + self.uname + '发布精品试用 《' + title + "》 来源：" + source_cn + " ")
        self.pay(status, response)

    def release_activity(self):
        """
        发布活动
        :return:
        """
        source = self.echo_source()
        order_url = get_order_url(highQualitySource(source).name)
        enter_type = self.echo_enter_type(source)
        self.release_basic(
            source=source,
            order_url=order_url,
            enter_type=enter_type)

    def pay(self, status, response):
        if status:
            tid = json.loads(response).get("data").split('/')[-1]
            logger.info("支付tid：%s 活动款" % tid)
            pay = PayQuantity(self.session)
            pay.test_pay_quantity(tid)


def main():
    while True:
        # 选择功能菜单
        menu_list.batch_release_high_quality_menu()
        # 选择
        choise = input("请输入您的选择: ")
        if choise in ('q', 'Q'):
            break
        seller_uname = input(u'请输入商家用户名: ')
        status = change_user_account_status(seller_uname)
        if not status:
            break
        if choise == '1':
            activity = Activity(seller_uname)
            activity.release_activity()
        elif choise == '2':
            activity = batch_activity(seller_uname)
            activity.release_activity()
            activity.pay_money()
        else:
            logger.info("没有对应的选项,请按选项输入...")
            break


if __name__ == "__main__":
    main()
    # activity = Activity('user0626')
    # activity.release_activity()
    # # activity.pay()
    # yaml_data = {'url': 'http://user.sk3.com/seller/quality/save_try_base', 'data': {'trySource': '', 'shop_id': '', 'shop_name': '淘宝特价店铺1542', 'url_order': 'https://market.m.taobao.com/app/nozomi/app-h5-detail/main/index.html?id=626765901971&sourceType=other&suid=b0798a2f-9746-4970-ae87-e2e627cb7e12&ut_sk=1.null.Copy.ltao_detail&un=6d649f5e0b1234fa8bd7bab98ffeb263&share_crt_v=1&spm=a2159r.13376460.0.0&sp_tk=Ylg1SWNsaER5UkU=&cpp=1&shareurl=true&short_name=h.4W5xnaa&bxsign=scdN96z62n3CgqAixv202BG9_VjQcGEKWTZgZg2HcLCH2ssNTytLhYAxzy0HDOY7kSsvbk5FCCa_ZoaHGSx3e4jiDuFcRIfwFDr0dlrHPdnoVA&sm=a638d3&app=chrome', 'title': '', 'cate_cid': 17, 'img_list': '', 'GrantNum': '', 'DateNum': 30, 'intro_on_app': '按摩披肩', 'is_apply_coupons': 0, 'coupons_url': '', 'Price': 50.9, 'before_order_price': 500, 'after_order_price': 10, 'order_quantity': 1, 'specs_limit': 1, 'pattern': 'type-1', 'item_No': 'x00', 'weight': '12g', 'spec': '大码', 'style': '中国红', 'volume': '100g', 'size': 'xxl', 'color': '京东红', 'other_specs': 'other', 'is_package': 0, 'try_extend[enter_type][]': '', 'try_extend_enter[4][total]': 8, 'try_extend_enter[4][search_styles][0][keyword]': '大码', 'try_extend_enter[4][search_styles][0][orderby_key]': 1, 'try_extend_enter[4][search_styles][0][orderby]': '单独的', 'try_extend_enter[4][search_styles][0][total]': 8, 'try_extend_enter[16][total]': 8, 'try_extend_enter[16][search_styles][0][scan_img]': 'tmp/2021/10/11/89406ae40e46714fc557079fc66d75f9.jpg', 'try_extend_enter[16][search_styles][0][orderby_key]': 1, 'try_extend_enter[16][search_styles][0][orderby]': '嘎嘎嘎', 'try_extend_enter[16][search_styles][0][total]': 8, 'try_extend_enter[32][total]': 8, 'try_extend_enter[32][search_styles][0][command]': '3幅治内容￥quaJciq5lE0$咑开ホ兆bao或掂击炼接 https://m.tb.cn/h.4bGwISf?sm=6f9781 至流览器【Mlekovita原装进口牛奶全脂1L*12 成人儿童孕', 'try_extend_enter[32][search_styles][0][orderby_key]': 1, 'try_extend_enter[32][search_styles][0][orderby]': 'ggg', 'try_extend_enter[32][search_styles][0][total]': 8, 'img_search': '', 'try_extend_enter[2][total]': 8, 'try_extend_enter[2][command]': '￥quaJciq5lE', 'try_extend_enter[8][total]': 8, 'try_extend_enter[8][scan_img]': 'tmp/2021/10/11/1185a3baf664dbf73f337fcf5cdd90b0.jpg', 'try_extend_enter[1][total]': 8, 'try_extend_added_task[4][total]': 8, 'try_extend_added_task[8][total]': 8, 'try_extend_added_task[8][content][1][q]': '答案是1', 'try_extend_added_task[8][content][1][a]': 1, 'try_extend_added_task[8][content][2][q]': '答案是2', 'try_extend_added_task[8][content][2][a]': 2, 'try_extend[added_task][]': [4, 8, 16, 32, 64, 128], 'try_extend_added_task[16][total]': 8, 'try_extend_added_task[32][total]': 8, 'try_extend_added_task[64][total]': 8, 'try_extend_added_task[128][total]': 8, 'try_extend[is_deep_experience]': 1, 'try_extend[max_task_time]': 10800, 'try_extend[min_wait_no_time]': 60, 'order_hours': 3, 'tips_no_involve_shikee': 1, 'tips_no_hurrying': 1, 'tips_no_credit_card': 1, 'tips_no_tao_jinbi': 1, 'tips_customer_service': 1, 'tips_no_offline': 1, 'is_hide_info': 0, 'try_extend[qq]': 21321312321, 'try_extend[wx]': 'lhb233333', 'try_extend[tel]': 13212341233, 'tid': '', 'token': '8d9816f67ad742df301bfb1ea7d8e113', 'try_extend[is_service_credit_query]': 0, 'try_extend[is_service_pass_sms]': 0, 'source': 13, 'shopId': 1698, 'Title': '淘特_精品深度_自选进店_刘', 'enter_type': [2], 'title_pic': 'tmp/2021/12/02/f0185437dde0c5ccd7ef45f7598ff4bc.jpg', 'search_pic': 'tmp/2021/12/02/99182fb8f684512361e1dc305ac2484c.jpg', 'qr_search_pic': 'tmp/2021/12/02/1e581bef9f5e3ab75cd637d19da6e1aa.jpg', 'qr_order_pic': 'tmp/2021/12/02/198b1ae551e9e0853ded77e5f7a74036.jpg'}, 'header': {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:52.0) Gecko/20100101 Firefox/52.0', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}}
    # enter_type = [4,2,1]
    # totle = sum([yaml_data.get("data").get("try_extend_enter[%s][total]" % t) for t in enter_type])
    # print(totle)
    # yaml_data.get("data").update(
    #                              shop_name=123,title=3123,url_order=123321,img_list=234,img_search=34534,
    #                              GrantNum= totle
    #                             )
    # activity.get_pic(2)
